package com.insigma.business.gateway.api.impl;


import com.insigma.business.gateway.dto.ApiServiceContext;
import com.insigma.business.gateway.dto.ServiceInfo;
import com.insigma.business.gateway.api.ServiceInvoker;
import com.insigma.business.gateway.exception.SpiException;
import com.insigma.business.qrcode.common.util.BizException;
import com.insigma.business.qrcode.common.util.ExceptionUtil;
import com.insigma.business.qrcode.common.vo.BaseResponse;
import com.insigma.business.qrcode.soldier.service.ApiAdapterService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.InvocationTargetException;
import java.util.List;


@Service
public class ApiAdapterServiceImpl implements ApiAdapterService {

    private final static Logger logger = LoggerFactory.getLogger(ApiAdapterServiceImpl.class);

    @Autowired
    private ServiceInvoker serviceInvoker;

    
    @Override
    public BaseResponse invokeApiService(final ApiServiceContext context,
                                         final String bizRequestDataMapStr) throws InvocationTargetException {
        try {
            return this.serviceInvoker.invoke(context, bizRequestDataMapStr);
        } catch (InvocationTargetException e) {
            ExceptionUtil.caughtWarn(logger, e, "业务方法异常");
            if (e.getTargetException() instanceof SpiException) {
                throw (SpiException) e.getTargetException();
            }
            if (e.getTargetException() instanceof BizException) {
                throw (BizException) e.getTargetException();
            }
            throw e;
        } catch (IllegalAccessException e) {
            ExceptionUtil.caughtWarn(logger, e, "调用目标方法权限不合法");
            throw new SpiException("服务端异常，请联系管理员");
        } catch (Exception e) {
            ExceptionUtil.caughtWarn(logger, e, "调用异常");
            throw new SpiException(e.getMessage());
        }
    }

    
    @Override
    public List<ServiceInfo> listServiceInfo() {
        return this.serviceInvoker.listServices();
    }
}
